import com.sun.deploy.util.StringUtils;

/**
 * @projectName: LeetCode
 * @package: PACKAGE_NAME
 * @className: Point6
 * @author: Mocrash
 * @description: TODO
 * @date: 2024/10/18 12:19
 * @version: 1.0
 */
public class Point8 {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int paypalishiring = solution.myAtoi("-120 12");
        System.out.println(paypalishiring);
    }

    private static class Solution {
        public int myAtoi(String s) {
            if (s.isEmpty()) {
                return 0;
            }
            int start = 0;
            while (start < s.length() && s.charAt(start) == ' ') {
                start += 1;
            }
            if (start >= s.length()) {
                return 0;
            }
            long op = 1;
            if (s.charAt(start) == '-') {
                op = -1;
                start += 1;
            } else if (s.charAt(start) == '+') {
                start += 1;
            }
            if (start >= s.length() || !isNum(s.charAt(start))) {
                return 0;
            }
            long res = toNum(s.charAt(start));
            start += 1;
            for (int i = start; i < s.length(); i++) {
                char curChar = s.charAt(i);
                if (!isNum(curChar)) {
                    return (int) res * (int) op;
                }
                res = res * 10 + toNum(curChar);
                if (res * op > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                } else if (res * op < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
            }
            return (int) res * (int) op;

        }

        private boolean isNum(char ch) {
            return ch <= '9' && ch >= '0';
        }

        private long toNum(char ch) {
            if (!isNum(ch)) throw new RuntimeException("ch不是一个数字");
            return ch - '0';
        }
    }
}
